import { IBaseProps, appName, getUserInfo, IFormProps, formItemLayout, getAllowMenus } from "../utils/common";
import React, { ReactNode } from "react";
import { connect } from 'dva';
import { Layout, Row, Col, Calendar, Icon, Dropdown, Modal, Form, Menu, Breadcrumb, Input, Button, message } from "antd";
import ProgressBar from 'simple-react-progress-bar';
import { withRouter } from "react-router-dom";
import { Link } from 'react-router-dom';
const Styles = require("../styles/layout.less");
import Menus, { IMenu, IBreadcrumb } from '../utils/menu';
import Enumerable from 'linq';

export interface IMainProps extends IFormProps {

}

class Main extends React.PureComponent<IMainProps, any>{
    constructor(props) {
        super(props);
        this.state = {};
    }

    componentDidMount() {

    }

    setNewModal = (flg) => {
        this.setState({
            visible: flg
        })
        this.reset();
    }

    reset = () => {
        this.props.form.resetFields();
    }

    //改密码
    updatePass = (obj, cb) => {
        let form = Object.assign({}, obj);
        this.props.dispatch!({
            type: 'user/updatePassword',
            payload: {
                form,
                callback: () => {
                    this.setNewModal(false);
                }
            }
        })
    }

    //modal 确认按钮 updatePass
    handleOk = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                this.updatePass(values, () => {
                    this.setNewModal(false);
                    message.info('密码修改成功');
                })
            }
        });
    }

    //登出
    logout = () => {
        this.props.history.push('/login');
    }

    // tomessage = () => {
    //     console.log(this.props.history);
    //     this.props.history.push('/message');
    // }

    handleClick = (e) => {
        // console.log(e);
        // this.setState({
        //     current: [`${e.key}`]
        // });
        this.props.history.push(e.key);
    }

    // openKeys = (openKeys) => {
    //     const latestOpenKey = openKeys.find(key => !(this.state!.openKeys!.indexOf(key) > -1));
    //     const latestCloseKey = this.state!.openKeys!.find(key => !(openKeys.indexOf(key) > -1));
    //     this.setState({ openKeys: [`${latestOpenKey}`] });
    // }

    // onCollapse = (collapsed: boolean) => {
    //     this.setState({ collapsed });
    // }

    render(): JSX.Element {
        const { getFieldDecorator } = this.props.form;
        const { loading = false } = this.props;
        const user = getUserInfo();
        const children: any = this.props.children;
        //console.log('children', children);
        const routers = children.props.children;
        //console.log(routers, this.props);
        const getBreadcrumb = (routers: Array<any>, pathname: string): Array<IBreadcrumb> => {
            return Enumerable.from(routers)
                .where(x => x && x['props'] && x['props'].path === pathname)
                .select(x => x['props'].breadcrumb)
                .firstOrDefault() || [];
        }
        const breadcrumb: Array<IBreadcrumb> = getBreadcrumb(routers, this.props.location.pathname);
        //console.log(breadcrumb);
        const ddmenu = (
            <Menu>
                <Menu.Item key="0">
                    <div onClick={() => this.setNewModal(true)}>修改密码</div>
                </Menu.Item>
                <Menu.Item key="1">
                    <div onClick={this.logout}>退出</div>
                </Menu.Item>
            </Menu>
        );
        /**
         * 
         * 创建菜单
         * @param {Array<IMenu>} menus 
         * @returns {*} 
         */
        const createMenu = (menus: Array<IMenu>): any => {
            try {
                return menus.map(item => {
                    let { title, key, path, breadcrumb, children, display = false, icon } = item;
                    if (display) {
                        /* 存在子集 */
                        if (children && children.length > 0) {
                            icon = icon || 'appstore';
                            return (
                                <Menu.SubMenu
                                    key={key}
                                    path={path}
                                    title={<span style={{ fontSize: 15 }}><Icon type={icon} /><span>{title}</span></span>}
                                >
                                    {createMenu(children)}
                                </Menu.SubMenu>
                            );
                        }
                        else {
                            icon = icon = 'setting';
                            return (
                                <Menu.Item key={path} path={path}>
                                    <span style={{ fontSize: 15 }}><Icon type={icon} /><span>{title}</span></span>
                                </Menu.Item>
                            );
                        }
                    }
                });
            } catch (e) {
                console.log(menus)
            }
        }

        const menus = createMenu(getAllowMenus());
        return (
            <div style={{ width: '100%', height: '100%' }}>
                <div style={{ height: '100vh' }}>
                    {/* <ProgressBar loading={this.props.loading} completed={!this.props.loading} resetLoading={() => { }} /> */}
                    <Layout style={{ height: '100%' }}>
                        <Layout.Header className={Styles.header}>
                            <Row>
                                <Col span={8} className={Styles.headertitle}>
                                    {appName}
                                </Col>
                                <Col span={8}></Col>
                                <Col span={8} style={{ padding: 20, fontSize: 16 }}>
                                    <Row type='flex' justify="end">
                                        <div>
                                            <Dropdown overlay={ddmenu} trigger={['click']}>
                                                <span style={{ cursor: 'Pointer' }}>
                                                    <Icon type="user" />
                                                    <span style={{ marginLeft: 5 }}>
                                                        {user && user.name ? user.name : '请登录'}
                                                    </span>
                                                    <Icon type="down" />
                                                </span>
                                            </Dropdown>
                                            {
                                                this.state!.visible ? <Modal
                                                    title={'修改密码'}
                                                    visible={this.state!.visible}
                                                    onOk={(e) => this.handleOk(e)}
                                                    onCancel={() => this.setNewModal(false)}
                                                    maskClosable={false}
                                                    confirmLoading={loading}
                                                >
                                                    <Form>
                                                        <Form.Item
                                                            {...formItemLayout}
                                                            label="原密码"
                                                        >
                                                            {getFieldDecorator('oldPassword', {
                                                                rules: [{
                                                                    required: true, message: '请输入原密码',
                                                                }],
                                                            })(
                                                                <Input type="password" placeholder="请输入原密码" />
                                                            )}
                                                        </Form.Item>
                                                        <Form.Item
                                                            {...formItemLayout}
                                                            label="新密码"
                                                        >
                                                            {getFieldDecorator('password', {
                                                                rules: [{
                                                                    required: true, message: '请输入新密码',
                                                                }],
                                                            })(
                                                                <Input type="password" placeholder="请输入新密码" />
                                                            )}
                                                        </Form.Item>
                                                    </Form>
                                                </Modal> : <div></div>
                                            }
                                        </div>
                                    </Row>
                                </Col>
                            </Row>
                        </Layout.Header>
                        <Layout>
                            <Layout.Sider>
                                <Menu
                                    theme="dark"
                                    //selectedKeys={this.state!.current}
                                    //openKeys={this.state!.openKeys}
                                    mode="inline"
                                    //inlineCollapsed={this.state!.collapsed}
                                    onClick={this.handleClick}
                                //onOpenChange={(openKeys) => this.openKeys(openKeys)}
                                >
                                    {menus}
                                </Menu>
                            </Layout.Sider>
                            <Layout.Content className={Styles.layoutcontent}>
                                <Row type="flex" justify="space-between" align="middle">
                                    <Breadcrumb className={Styles.breadcrumb}>
                                        {
                                            breadcrumb.map((item, key) => {
                                                return <Breadcrumb.Item key={key}>{item.name}</Breadcrumb.Item>
                                            })
                                        }
                                    </Breadcrumb>
                                    {
                                        breadcrumb.length < 3 ? undefined : <Button size="small" className={Styles.goback} onClick={this.props.history.goBack}>返回</Button>
                                    }
                                </Row>
                                <div className={Styles.content}>
                                    {this.props.children}
                                </div>
                            </Layout.Content>
                        </Layout>
                    </Layout>
                </div>
            </div>
        )
    }
}

export default withRouter(connect()(Form.create()(Main)));